<template>
  <page-loading :show="showPage" mode="if">
	<view class="my-favorites">
    <view class="line"></view>
    <!-- 顶部tab -->
		<view class="tab-box">
			<u-tabs-swiper 
        ref="uTabs" 
        :list="list" 
        :current="current" 
        @change="tabsChange" 
        :is-scroll="false"
        active-color="#333"
        inactive-color="#666"
        swiperWidth="750" 
        bar-width="80"
        :bar-style="barActiveStyle"
      ></u-tabs-swiper>
		</view>
    
		<view class="content">
        <swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
        	<swiper-item class="swiper-item" v-for="(item, index) in result" :key="index" catchtouchmove="stopTouchMove" @touchmove.stop.prevent>
        		<scroll-view class="scroll-view" scroll-y @scrolltolower="onLoadmore">
        			<u-empty mode="favor" v-if="item.data.length <= 0 && item.isEnd"></u-empty>
              <uni-swipe-action v-else>
                <!-- 如果引用是第一项，使用新车样式模板 -->
                <block v-for="(i, k) in item.data" :key="k">
                  <template v-if="index === 0">
                    <new-car-item @onClickAction="onClickAction" :item="i" :item-index="k" />
                  </template>
                  <!-- 如果引用是第二项，使用新车样式模板 -->
                  <template v-if="index === 1">
                    <maintain-item @onClickAction="onClickAction" :item="i" :item-index="k" />
                  </template>
                  <!-- 如果引用是第三项，使用新车样式模板 -->
                  <template v-if="index === 2">
                    <store-item @onClickAction="onClickAction" :item="i" :item-index="k" />
                  </template>
                </block>
              </uni-swipe-action>
              
              <view class="loading-status mt-20" v-if="item.data.length > 0"><u-loadmore :status="item.status" /></view>
        		</scroll-view>
        	</swiper-item>
          
        </swiper>
    </view>
    
    <!-- 分享组件 -->
    <share v-model="shareShow" :is-download="false" @change="onChangeShare" />
	</view>
  </page-loading>
</template>

<script>
import uniSwipeAction from '@/components/uni-swipe/uni-swipe-action/uni-swipe-action.vue'
import newCarItem from './components/newCarItem.vue' // 新车样式组件
import maintainItem from './components/maintainItem.vue' //保养样式组件
import storeItem from './components/storeItem.vue' //保养样式组件
import {share} from '@/utils/common-api.js' // 导入分享方法
export default {
  components: {
    uniSwipeAction,
    newCarItem,
    maintainItem,
    storeItem
  },
  data() {
    return {
      barActiveStyle: {
        'background': 'linear-gradient(0deg, #FBB000, #FFE23E)'
      }, // tab选中是下划线样式
      list: [{
        name: '新车'
      }, {
        name: '保养'
      }, {
        name: '店铺'
      }], // tab数据列表
      current: 0, // tabs组件的current值
      swiperCurrent: 0, // swiper组件的current值
      shareShow: false, // 分享弹窗显示状态
      result: [
        {
          type: 2,
          pageIndex: 1,
          pageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        }, // 新车请求数据和结果列表
        {
          type: 3,
          pageIndex: 1,
          pageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          type: 4,
          pageIndex: 1,
          pageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        }
      ],
      location: {},
      currentShareData: null,
      showPage: false
    };
  },
  onLoad() {
    this.$commen.getLocation(data => {
      this.location = data
      this.getList()
    })
    
    // this.$api.store.addFavorite({favorite_type: 4, carstore_id: '4d3219a6204245dca2360ce160d1dfb6'}).then(data=>{
    //   console.log(data)
    // })
  },
  methods: {
    // 点击tan切换
    tabsChange(index) {
      this.swiperCurrent = index;
      this.getList()
    },
    transition(e) {
      let dx = e.detail.dx;
      this.$refs.uTabs.setDx(dx);
    },
    animationfinish(e) {
      let current = e.detail.current;
      this.$refs.uTabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
    },
    // 禁用swiper滑动
    stopTouchMove() {
      return false
    },
    /*
      点击列表菜单
      @param {Object} data.type 操作类型 (share，delete)
      @param {Object} data.item 当前选择项的数据
      @param {Object} data.index 当前选择项在数组中的索引
      params: 
    */
    onClickAction(data) {
      if(data.type === 'share') {
        this.shareShow = true
        this.currentShareData = data
      } else {
        this.deleteCurrentItem(data)
      }
    },
    // 点击分享
    onChangeShare(data) {
      let params = {}
      let current = this.currentShareData.item
      if(this.swiperCurrent === 0){
        params.title = current.configuration_name
        params.summary = current.configuration_name
        params.imageUrl = current.goodimg
        if(current.is_loans === 1) {
          params.href = this.$config.WEBURL + `index.html#/pages_commodity/giantnengjiangDetails/giantnengjiangDetails?goodid=${current.newcar_id}`
        } else {
          params.href = this.$config.WEBURL + `index.html#/pages_commodity/sourceDetails/sourceDetails?goodid=${current.newcar_id}`
        }
      }
      if (this.swiperCurrent === 1){
        params.title = current.store_name
        params.summary = current.store_name
        params.imageUrl = current.store_topimg
        params.href = this.$config.WEBURL + `index.html#/pages_store/carMaintenanceStore/details/details?storeid==${current.bystore_id}`
      }
      if (this.swiperCurrent === 2){
        params.title = current.store_name
        params.summary = current.store_name
        params.imageUrl = current.logoImg
        params.href = this.$config.WEBURL + `index.html#/pages_store/newCarStore/index/index?storeid=${current.carstore_id}`
      } 
      share({
        scene: data,
        type: 0,
        ...params
      }, () => {
        
      })
    },
    // 删除选择项
    async deleteCurrentItem(data) {
      uni.showLoading({
        title: '加载中'
      })
      try{
        let res = await this.$api.store.cancelFavorite({
          id: data.item.id
        })
        uni.hideLoading()
        if(res.code === 200) {
          this.result[this.swiperCurrent].data.splice(data.index, 1)
        }
        uni.showToast({
          icon: 'none',
          title: res.data
        })
      }catch(e){
        uni.hideLoading()
      }
      setTimeout(() => {
        uni.hideLoading()
      }, 300)
    },
    // scroll-view到底部加载更多
    onLoadmore() {
      this.getList()
    },
    // 计算总共有多少页
    pageCount (totalnum,limit){
      return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0
    },
    async getList (type) {
      let {getFavoriteCEntityCarList, getFavoriteCEntityBYList, getFavoriteCEntityStroeList} = this.$api.store;
      let list = this.result[this.swiperCurrent]
      if (type) {
        list.page = 1
        list.isEnd = false
        list.loading = false
        list.status = 'loading'
      }
      if (list.loading || list.isEnd) {
        return false
      }
      list.loading = true
      this.$set(this.result, this.activeTab, list)
      
      try{
        let res = {}
        let params = {
          pageIndex: list.pageIndex,
          pageSize: list.pageSize,
          favorite_type: list.type,
          dlat: this.location.lat,
          dlon: this.location.lon
        }
        if(this.swiperCurrent === 0) {
          res = await getFavoriteCEntityCarList(params)
        }
        if(this.swiperCurrent === 1) {
          res = await getFavoriteCEntityBYList(params)
        }
        if(this.swiperCurrent === 2) {
          res = await getFavoriteCEntityStroeList(params)
        }
        let reslist = res.data.list
        this.showPage = true
        if (type) {
          reslist.data = []
        }
        
        if(reslist.length <= 0 || list.pageIndex >= this.pageCount(res.data.total, list.pageSize)) {
          list.isEnd = true
          list.status = 'nomore'
        }
        
        if (reslist.length > 0) {
          list.data = list.data.concat(reslist)
          list.pageIndex = list.pageIndex + 1
        }
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }catch(e){
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }
    }
  }
};
</script>

<style>
page{
  background-color: #f6f6f6;
}
</style>

<style lang="scss">
page{
  height: 100%;
}
.my-favorites{
  height: 100%;
  display: flex;
  flex-direction: column;
  .line{
    background-color: #f6f6f6;
    height: 2rpx;
    width: 100%;
  }
  .content{
    flex: 1;
    overflow: hidden;
    margin-top: 22rpx;
  }
  .swiper, .swiper-item, .scroll-view{
    height: 100%;
  }
}

/deep/ .item-swipe:last-child .new-car-item{
  border-bottom: none;
}
</style>